package com.ruoyi.shop.util;

import com.ruoyi.common.utils.DateUtils;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @Author Alan Zhang
 * @Date 2021/9/25 15:17
 */
public class GenNumberUtils {
    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
    private static final String YYYYMMDD = "yyyyMMdd";
    private static final Random RANDOM = new SecureRandom();
    private static final int n = 10000;

    /**
     * 生成随机文件名：当前年月日时分秒+五位随机数
     *
     * @return
     */
    public static String getRandomStr() {
        StringBuilder sb = new StringBuilder();
        simpleDateFormat.applyPattern(YYYYMMDD);
        sb.append(simpleDateFormat.format(System.currentTimeMillis()));
        sb.append((RANDOM.nextInt(99999 - n + 1) + n));// 获取5位随机数
        return sb.toString();// 当前时间
    }

    /**
     * 支付交易ID
     */
    public static String getBundleId() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String tradeno = dateFormat.format(new Date());
        String str = "000000" + (int) (Math.random() * 1000000);
        tradeno = tradeno + str.substring(str.length() - 6);
        return tradeno;
    }

    /**
     * 获取随机字符串 Str
     *
     * @return String 随机字符串
     */
    private static String generateStr() {
        char[] nonceChars = new char[6];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 当前年月日时分秒+六位随机数
     * @param prefix 前缀
     * @return
     */
    public static String genOrderNoStr(String prefix) {
        StringBuilder sb = new StringBuilder();
        simpleDateFormat.applyPattern(DateUtils.YYYYMMDDHHMMSS);
        sb.append(simpleDateFormat.format(System.currentTimeMillis()));
        sb.append(generateStr());
        return sb.toString();
    }

    private static final SnowFlake SNOW_FLAKE = new SnowFlake(1, 1);

    public static String genOrderNS() {
        return String.valueOf(SNOW_FLAKE.genNextId());
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
